import re
import json
import time
import hashlib
import quickjs
import requests

class DOUYU():
    def getInfos(self, params):
        header = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'
        }
        rid = params['rid']
        did = '10000000000000000000000000001501'
        t = str(int(time.time()))
        session = requests.Session()
        r = session.get('https://m.douyu.com/' + str(rid), headers=header, timeout=15)
        result = re.search(r'(function ub98484234.*)\s(var.*)', r.text).group()
        funcUb9 = re.sub(r'eval.*;}', 'strc;}', result)
        jsFunc = quickjs.Function('ub98484234', funcUb9)
        res = jsFunc()
        v = re.search(r'v=(\d+)', res).group(1)
        rb = hashlib.md5((rid + did + t + v).encode()).hexdigest()
        funcSign = re.sub(r'return rt;}\);?', 'return rt;}', res)
        funcSign = funcSign.replace('(function (', 'function sign(')
        funcSign = funcSign.replace('CryptoJS.MD5(cb).toString()', '"' + rb + '"')
        jsFunc = quickjs.Function('sign', funcSign)
        res = jsFunc(rid, did, t)
        res += '&ver=219032101&rid={}&rate=-1'.format(rid)
        url = 'https://m.douyu.com/api/room/ratestream'
        r = session.post(url, params=res, headers=header, timeout=15)
        session.close()
        data = json.loads(r.text)['data']
        if 'url' in data:
            url = data['url']
        else:
            raise Exception('错误：未找到直播地址')
        return url
